package heathot.bookservice;

import heathot.dao.impl.BookDao;
import heathot.dao.impl.BookDaoimpl;
import heathot.entiy.Book;
import heathot.entiy.BookPager;
import heathot.entiy.Car;
import heathot.entiy.CarItem;

import java.util.List;

public class BookServiceimpl implements BookService {
	private BookDao dao;
	
	public BookServiceimpl(){
		dao= new BookDaoimpl();
	}
	
	@Override
	public int addBook(Book book) {
		return dao.addBook(book);
	}

	@Override
	public int deleteBook(int id) {
		return dao.deleteBook(id);
	}

	@Override
	public int upadateBook(Book book) {
		return dao.upadateBook(book);
	}

	@Override
	public Book selectBook(int id) {
		return dao.selectBook(id);
	}

	@Override
	public List<Book> selectBooks() {
		return dao.selectBooks();
	}

	@Override
	public BookPager selectBookByPage(int page, int pagesize) {
		return dao.selectBookByPage(page, pagesize);
	}
		
		public String updateCarItem(int id,int count,Car car){
			CarItem temp =null;
			for(CarItem item : car.getItems()){
				if(item.getBook().getId()==id){
					temp=item;
				}
			}
			if(temp!=null){
				temp.setCount(count);
			}
			float itemPrice = temp.getTotalPrice();
			float carPrice  = car.getTotal();
			return itemPrice+","+carPrice;
		}
		
	@Override
	public void addToCar(int id, Car car) {
		CarItem temp = null;
		for(CarItem item : car.getItems()){
			if(item.getBook().getId()==id){
				temp=item;
				break;
			}
		}
		if(temp!=null){
			temp.setCount(temp.getCount()+1);
		}
		else{
			Book book = dao.selectBook(id);
			CarItem ci = new CarItem(book,1);
			car.addItem(ci);
		}
	}
	
	public void deleteCar(int id,Car car){
		CarItem temp = null;
		for(CarItem item : car.getItems()){
			if(item.getBook().getId()==id){
				temp=item;
				break;
			}
		}
		
		car.getItems().remove(temp);
	}
}
